//
//  AppDelegate.m
//  MusicOnline
//
//  Created by Le Thanh Hai on 6/9/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "MasterViewController.h"
#import "DownloadViewController.h"
#import "PlayerViewController.h"
#import "AudioStreamer.h"
#import "NetworkConnection.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize navigationController = _navigationController;
@synthesize tabbarController = _tabbarController;
@synthesize downloadViewcontroller = _downloadViewcontroller;
@synthesize uiIsVisible;
@synthesize viewController;

- (void)dealloc
{
    [viewController release];
    [_window release];
    [_navigationController release];
    [super dealloc];
}

- (void)presentAlertWithTitle:(NSNotification *)notification
{
	if (!uiIsVisible)
		return;
	NSString *title = [[notification userInfo] objectForKey:@"title"];
	NSString *message = [[notification userInfo] objectForKey:@"message"];
	UIAlertView *alert = [
						  [[UIAlertView alloc]
						   initWithTitle:title
						   message:message
						   delegate:self
						   cancelButtonTitle:NSLocalizedString(@"OK", @"")
						   otherButtonTitles: nil]
						  autorelease];
	[alert
	 performSelector:@selector(show)
	 onThread:[NSThread mainThread]
	 withObject:nil
	 waitUntilDone:NO];
}

- (void)splashStartup
{
    self.window.hidden = NO;
    splashImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    splashImage.image = [UIImage imageNamed:@"Default.png"];
    [self.window addSubview:splashImage];
    [self.tabbarController setSelectedIndex:0];
    [NSTimer scheduledTimerWithTimeInterval:1.5
                                     target:self
                                   selector:@selector(clearSplashImage)
                                   userInfo:nil
                                    repeats:NO];
    
}

- (void)clearSplashImage
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    [UIView setAnimationDuration: 3.0];
    [UIView setAnimationDelegate: self];
    splashImage.alpha = 0.0;
    [UIView commitAnimations];
    
    [splashImage removeFromSuperview];
    [splashImage release];
    
    if (timeoutTimer) {
        [timeoutTimer invalidate];
        timeoutTimer = nil;
    }
    
    [self.window bringSubviewToFront:busyView];
}

- (void)showBusyView:(BOOL)YesOrNo
{
    busyView.hidden = !YesOrNo;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.

    MasterViewController *masterViewController = [[[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil] autorelease];


    self.navigationController = [[[UINavigationController alloc] initWithRootViewController:masterViewController] autorelease];
    
    //
    self.downloadViewcontroller = [[DownloadViewController alloc] initWithNibName:@"DownloadViewController" bundle:nil];
    
    self.tabbarController = [[UITabBarController alloc] init];
    self.tabbarController.viewControllers = [NSArray arrayWithObjects:self.navigationController, self.downloadViewcontroller, nil];
//    [(UIViewController *)[self.tabbarController.viewControllers objectAtIndex:2] tabBarItem].badgeValue = @"1";
    //    [[(UIViewController *)[self.tabbarController.viewControllers objectAtIndex:2] tabBarItem] ];
    
    
    
    UITabBarItem *firstItem1 = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:1];
    
    self.tabbarController.tabBarItem = firstItem1;

    self.window.rootViewController = self.tabbarController;
    busyView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    busyView.backgroundColor = [UIColor grayColor];
    busyView.frame = CGRectMake(0, 0, 80, 80);
    busyView.alpha = 0.6;
    busyView.center = CGPointMake(160, 240);
    [busyView.layer setCornerRadius:10];
    
    [busyView startAnimating];
    [self.window addSubview:busyView];
    [self.window makeKeyAndVisible];
    [self splashStartup];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    self.uiIsVisible = NO;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    self.window.hidden = YES;
    self.uiIsVisible = NO;
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
	self.uiIsVisible = YES;
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentAlertWithTitle:)name:ASPresentAlertWithTitleNotification object:nil];
    
    int appState = [[UIApplication sharedApplication] applicationState];
    switch (appState) {
        case UIApplicationStateActive:
            break;
        case UIApplicationStateBackground:
            [self splashStartup];
            break;
        default:
            break;
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    self.uiIsVisible = YES;
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
	self.uiIsVisible = NO;
	[[NSNotificationCenter defaultCenter] removeObserver:self name:ASPresentAlertWithTitleNotification object:nil];
}

@end
